import React, { FC } from 'react';
import { FormInstance } from 'antd/lib/form';
import { Spin } from 'antd';
import ProTable, { ProColumns } from '@/components/ProTable';
import useHoxModel from '../../../../useHoxModel';
import { AddDoorType, AreaListReturnProps } from '../../../../API';
import { useUnmount, useUpdateEffect } from 'ahooks';
import styles from './index.less';
import { pick } from 'lodash';
import { arrayToEnum } from '@/utils/utils';
import arrayToTree from './arrayToTree';

const AddForm: FC<{
  formRef: React.MutableRefObject<FormInstance | undefined>;
  isEdit?: boolean;
}> = ({ formRef, isEdit }) => {
  const {
    formAreaList = [],
    getFormAreaList,
    controllerType,
    doorInfo = {},
    doorInfoLoading,
    dispatch,
    doorOpenType,
    planMode,
  } = useHoxModel((model) => [
    model.planMode,
    model.controllerType,
    model.formAreaList,
    model.doorInfo,
    model.doorInfoLoading,
    model.doorOpenType,
  ]);
  useUnmount(() => {
    formRef.current?.resetFields();
  });
  //控制器类型枚举
  const controllerTypeEnum = arrayToEnum<AreaListReturnProps>(controllerType);
  //计划模板枚举
  const planModeListEnum = arrayToEnum<AreaListReturnProps>(planMode?.list);
  //开门方式枚举
  const doorOpenTypeEnum = arrayToEnum<AreaListReturnProps>(doorOpenType, 'type');

  const loadData = async (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    let res = await getFormAreaList({ id: targetOption.value });
    if (res.result === 0) {
      targetOption.loading = false;
      targetOption.children = res?.data.map((item: any) => {
        return {
          label: item.name,
          value: item.id,
          isLeaf: item.isRegion,
        };
      });
      dispatch({ formAreaList });
    }
  };

  useUpdateEffect(() => {
    if (doorInfo && JSON.stringify(doorInfo) !== '{}') {
      const fields = pick(doorInfo, [
        'adr',
        'alias',
        'controllerType',
        'deviceNo',
        'ip',
        'openType',
        'name',
        'port',
      ]);
      let currentAreaList = arrayToTree(doorInfo.areaPath);
      dispatch({ formAreaList: currentAreaList });

      formRef.current?.setFieldsValue({
        ...fields,
        openType: fields.openType.split(','),
        regionId:
          doorInfo.areaPath.map((item: AreaListReturnProps) => {
            return item.id;
          }) || [],
        controllerType: fields.controllerType.toString(),
      });
    }
  }, [doorInfo]);

  const columns: ProColumns<AddDoorType>[] = [
    {
      key: 'doorInfo',
      renderFormItem: () => <div>门信息参数</div>,
    },
    {
      title: '区域选择:',
      dataIndex: 'regionId',
      colItemSpan: 12,
      valueType: 'cascader',
      formItemProps: {
        options: formAreaList,
        loadData,
        changeOnSelect: true,
      },
      rules: [
        {
          required: true,
        },
      ],
    },
    {
      title: '门名称:',
      dataIndex: 'name',
      colItemSpan: 12,
      rules: [
        {
          required: true,
        },
      ],
    },
    {
      title: '编号:',
      dataIndex: 'deviceNo',
      colItemSpan: 12,
    },
    {
      title: '计划模板:',
      dataIndex: 'planMode',
      colItemSpan: 12,
      valueEnum: planModeListEnum,
    },
    {
      key: 'controller',
      renderFormItem: () => <div>控制器参数</div>,
    },
    {
      title: '控制器类型:',
      dataIndex: 'controllerType',
      colItemSpan: 12,
      valueEnum: controllerTypeEnum,
      rules: [
        {
          required: true,
        },
      ],
    },
    {
      title: '设备IP:',
      colItemSpan: 12,
      dataIndex: 'ip',
      rules: [
        {
          required: true,
        },
        {
          pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
          message: '请输入正确的IP！',
        },
      ],
    },
    {
      title: '地址:',
      dataIndex: 'adr',
      colItemSpan: 12,
      rules: [
        {
          required: true,
        },
        {
          pattern: /^(([0-9])|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))$/,
          message: '请输入0 - 255的整数！',
        },
      ],
    },
    {
      title: '端口:',
      dataIndex: 'port',
      colItemSpan: 12,
      rules: [
        {
          required: true,
        },
        {
          pattern: /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/,
          message: '请输入正确的端口！',
        },
      ],
    },
    {
      title: '开门方式:',
      dataIndex: 'openType',
      formItemProps: {
        mode: 'multiple',
      },

      rules: [
        {
          required: true,
        },
      ],
      valueEnum: doorOpenTypeEnum,
    },
    {
      title: '备注:',
      dataIndex: 'rec',
      valueType: 'textarea',
    },
  ];

  return (
    <Spin spinning={doorInfoLoading}>
      <div className={styles['edit-form']}>
        <ProTable<AddDoorType>
          form={{ layout: 'vertical', autoComplete: 'off' }}
          columns={columns}
          type={'form'}
          formRef={formRef}
        />
      </div>
    </Spin>
  );
};
export default AddForm;
